<template>
	<view>
		<uni-datetime-picker 
			v-model="val" 
			type="daterange" 
			rangeSeparator="至" 
			:start-placeholder="startPlaceholder"
			:end-placeholder="endPlaceholder"
			:disabled="disabled || !writable"
			:clear-icon="clearable"
			return-type="string"
			@change="datePicker"
		/>
		<view v-show="required && validator" class="requiredMessage">{{ requiredMessage }}</view>
	</view>
</template>

<script>
import UniDatetimePicker from '../uni-datetime-picker/uni-datetime-picker.vue'
export default {
	data() {
		return {
			val: [],
			show: false,
			validator: false,
		};
	},
	components: { UniDatetimePicker },
	props: {
		value: {
			type: Array,
			default: () => []
		},
		required: {
			type: Boolean,
			default: false
		},
		requiredMessage: {
			type: String,
			default: '值不能为空'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		writable: {
			type: Boolean,
			default: true
		},
		clearable: {
			type: Boolean,
			default: false
		},
		startPlaceholder: {
			type: String,
			default: '开始日期'
		},
		endPlaceholder: {
			type: String,
			default: '结束日期'
		}
	},
	computed: {
		validateStatus() {
			return this.$store?.state?.validate?.status || false
		}
	},
	watch: {
		value: {
			handler () {
				this.val = this.value || []
			},
			immediate: true,
			deep: true
		},
		validateStatus() {
			if(this.validateStatus && this.required) {
				if(!this.val.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		},
		val() {
			if(this.validateStatus && this.required) {
				if(!this.val.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			}
		}
	},
	methods: {
		// 确认选中日期范围
		datePicker(dates) {
			this.val = dates
			this.show = false
			this.$emit('input', this.val)
		},
		// 清空日期
		clearDate() {
			if(!this.clearable) {
				return
			}
			this.val = []
			this.$emit('input', this.val)
		}
	}
}
</script>

<style scoped>
.requiredMessage {
	width: 100%;
	height: 50rpx;
	line-height: 50rpx;
	color: #f56c6c;
	font-size: 22rpx;
}
</style>